import axios from "axios";
import { Message } from "element-ui";
import { store } from "@/store";

let baseUrl = "/api";
if (process.env.NODE_ENV === "development") {
//   baseUrl = "http://192.168.104.12:5012/api";
  baseUrl = "http://127.0.0.1:4523/m1/3151035-1456178-default";
  console.log("开发环境");
} else {
  console.log("生产环境");
}

export const myBaseUrl = baseUrl;
// 错误提示
const requestErrTip = (msg) => {
  Message.error({
    message: msg,
    type: "error",
    offset: document.documentElement.clientHeight / 3,
  });
};

const instance = axios.create({
  baseURL: baseUrl,
  timeout: 5000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    if (config.method !== "get") {
        if (store.state.auth.needAuth) {
            const isAuth = store.state.auth.isAuthenticated;

            if (!isAuth) {
                // 延迟1.5s发送验证事件
                setTimeout(() => {
                    store.dispatch('auth/sendNeedAuthenticateUserEvent');
                }, 1500);
                return Promise.reject(new Error("更改操作需要验证账号！"));
            }
        }
    }
    return config;
  },
  (err) => {
    console.error("请求拦截器错误：", err);
    requestErrTip(err.message);
    return Promise.reject(err);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (res) => {
    const resData = res.data;
    if (resData.status !== 200) {
      requestErrTip(resData.message || "请求失败");
      return Promise.reject(new Error(resData.message || "请求失败"));
    }
    return resData;
  },
  (err) => {
    console.error("响应拦截器错误：", err);
    requestErrTip(err.message);
    return Promise.reject(err);
  }
);

export function request(config) {
  return instance(config).catch((err) => {
    console.error("请求错误：", err.message || err);
    return Promise.resolve({});
  });
}
